//
//  AppController.m
//  MediaInfoGUI
//
//  Created by Olivier Larivain on 1/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import "DocumentInfo.h"
#import "DetailLevel.h"
#import "MediaInfoController.h"
#import "MediaInfoModel.h"
#import "DocumentLoadOperation.h"

@interface AppController(hidden)
- (void) enableFileDropDown;
- (void) refreshView;
- (void) mediaInfoLoadDidEnd;
- (void) showProgressIndicator: (BOOL) show;
@end


@implementation AppController

#pragma mark constructor
- (id) init
{
  self = [super init];
  if(!self)
  {
    return nil;
  }
  queue = [[NSOperationQueue alloc] init];
  [queue retain];
  return self;
}

#pragma mark UI Handlers
- (IBAction) open:(id) sender
{
    // make sure we cancel the previous operation
  [queue cancelAllOperations];
  [queue waitUntilAllOperationsAreFinished];
  
  [self showProgressIndicator:FALSE];
  NSOpenPanel *panel = [NSOpenPanel openPanel];
  [panel setCanChooseFiles:TRUE];
  [panel setCanChooseDirectories:TRUE];
  [panel setResolvesAliases:TRUE];
  [panel setAllowsMultipleSelection: TRUE];
  [panel setMessage:@"Select Media Files Or Folders"];
  
  [panel beginSheetForDirectory:NSHomeDirectory() file:nil modalForWindow:window modalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

- (void)openPanelDidEnd:(NSOpenPanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
  if(returnCode == NSFileHandlingPanelOKButton)
  {
    [self openURLs: [panel URLs]];
  }
}
     
- (void) openFilenames: (NSArray *) files
{
  [fileDropDown removeAllItems];
  [fileDropDown setEnabled:FALSE];
  [allCheckBox setEnabled: FALSE];
  [allCheckBox setState: NSOffState];
  
  [documentInfosArrayController setSelectionIndex: -1];
  
  [self showProgressIndicator: TRUE];
  DocumentLoadOperation *loadOperation = [[DocumentLoadOperation alloc] initWithFields: self miController: mediaInfoController filenames: files detailLevel: currentDetailLevel];
  [queue addOperation:loadOperation];
}

-(void) openURLs: (NSArray *) URLs
{
  NSMutableArray *filenames = [[NSMutableArray alloc] initWithCapacity:[URLs count]];
  for (NSURL *url in URLs)
  {
    [filenames addObject:[url path]];
  }
  [self openFilenames:filenames];
}

- (void) loadFinished
{
  [mediaInfoController refreshDocument:[[model documentInfos] objectAtIndex:0] detailLevel: currentDetailLevel];
  
  [allCheckBox setEnabled: [model documentCount] > 1];
  for(DocumentInfo *info in [model documentInfos])
  {
    NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:[info name] action:@selector(documentSelectionChanged:) keyEquivalent:@""];
    [menuItem setTarget:self];
    
    [[fileDropDown menu] addItem:menuItem];
  }
  
  BOOL singleFile =[[model documentInfos] count] == 1;
  [fileDropDown setEnabled: TRUE];
  [[fileDropDown cell] setArrowPosition: singleFile ? NSPopUpNoArrow : NSPopUpArrowAtBottom];
  NSRect initialFrame = [fileDropDown frame];
  [fileDropDown sizeToFit];
  NSPoint checkBoxOrigin = [allCheckBox frame].origin;
  
  checkBoxOrigin.x += [fileDropDown frame].size.width - initialFrame.size.width;
  [allCheckBox setFrameOrigin:checkBoxOrigin];
  
  [self showProgressIndicator: FALSE];
}

- (void) showProgressIndicator: (BOOL) show
{
  if(show)
  {
    [progressIndicator startAnimation:self];  
  }
  else 
  {
    [progressIndicator stopAnimation:self];
  }

  [progressBox setHidden:!show];

}

- (void) enableFileDropDown
{
  if([allCheckBox isTransparent])
  {
    [fileDropDown setEnabled:[[model documentInfos] count]>0];  
  }
  else
  {
    [fileDropDown setEnabled:!([allCheckBox state] == NSOnState) && [[model documentInfos] count]>0];  
  }
}

- (void) allCheckBoxClicked:(id) sender
{
  [self enableFileDropDown];
  if([sender state] == NSOnState)
  {
      [self showProgressIndicator: TRUE];
  }
  [self refreshView];
  if([sender state] == NSOnState)
  {
    [self showProgressIndicator: FALSE];
  }
}


- (void) documentSelectionChanged:(id) sender
{
  int index = [fileDropDown indexOfItem:sender];
  [documentInfosArrayController setSelectionIndex: index];
  [self refreshView];
}

-(void) refreshView
{
  
  if([allCheckBox state] == NSOnState && ![allCheckBox isTransparent])
  {
    [mediaInfoController refreshAllDocuments:currentDetailLevel];
  }
  else 
  {
    int index = [documentInfosArrayController selectionIndex] < 0 ? 0 : [documentInfosArrayController selectionIndex];
    [mediaInfoController refreshDocument:[[model documentInfos] objectAtIndex:index] detailLevel: currentDetailLevel];
    [documentInfosArrayController setSelectionIndex: index];
  }
  
}


- (void) setViewMode:(DetailLevel) mode
{
  NSView *view;
  currentDetailLevel = mode;
  switch(mode)
  {
    case BASIC:
      view = simpleView;
      [allCheckBox setTransparent:TRUE];
      [self enableFileDropDown];
      break;
    case SHEET:
      view = sheetView;
      break;
    case HTML:
      view = HtmlView;
      [allCheckBox setTransparent: FALSE];
      [allCheckBox setEnabled: [model documentCount] > 1];
      [self enableFileDropDown];
      break;
    case TREE:
      view = treeView;
      break;
    case TEXT:
      view = textView;
      [allCheckBox setTransparent:FALSE];
      [allCheckBox setEnabled: [model documentCount] > 1];
      [self enableFileDropDown];
      break;
  }
  [viewStack setContentView: view];
  
  if(![allCheckBox isTransparent] && [allCheckBox state] == NSOnState)
  {
    [self showProgressIndicator:TRUE];
  }
  if([[model documentInfos] count] > 0)
  {
    [self refreshView];
  }
  if(![allCheckBox isTransparent] && [allCheckBox state] == NSOnState)
  {
    [self showProgressIndicator:FALSE];
  }
}

- (void)awakeFromNib 
{
  [self setViewMode: BASIC];
}

- (IBAction) about:(id) sender
{
  if(aboutWindowController == nil)
  {
    aboutWindowController = [[NSWindowController alloc] initWithWindow: aboutWindow];
  }
  [aboutWindowController showWindow:aboutWindowController];    
}

- (IBAction) preferences:(id) sender
{
  if(preferencesWindowController == nil)
  {
    preferencesWindowController = [[NSWindowController alloc] initWithWindow: preferencesWindow];
  }
  [preferencesWindowController showWindow:preferencesWindowController];    
  
}

- (IBAction) openDonateURL:(id) sender
{
  [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString:@"http://mediainfo.sourceforge.net/en/Donate"] ];
}

@end
